import React from 'react';
import ajax from 'superagent';

import Search from '../../components/search/Search';
import MainSortTab from '../../components/mainSortTab/MainSortTab';
import Sort from '../../components/sort/Sort';


class MainClub extends React.Component {
    constructor(props) {
        super(props);
        this.displayName = 'MainClub';
        this.url = "/api/teams/";

        this.sort_mode_choices = {
            0: '-score',  // default
            1: 'pingyin',
        };

        this.state = {
            sort_mode: this.sort_mode_choices[0],
            data: [],
        };
    }

    fetchingData( ordering ) {
        this.serverRequest = ajax.get(this.url)
            .query({'ordering': ordering})
            .end(function(error, response)  {

                if( !error && response ) {

                    let data_origin = response.body;
                    let data = [];  // clean existed data

                    // 将返回的数据整理成需要的样子
                    data_origin.map(( club, index ) => {
                        data.push({
                            id: club.id,
                            rank: club.ranking,
                            img: club.avatar_url,
                            name: club.name,
                            score: club.score,
                            letter: club.pingyin,
                        });
                    });

                    this.setState({
                        data: data,
                        sort_mode: ordering,
                    });
                } else {
                    console.error(`Error fetching ${name} `, error);
                }
        }.bind(this));
    }

    componentDidMount() {
        this.fetchingData(this.state.sort_mode);
    }

    componentWillUnmount() {
        this.serverRequest.abort();
    }

    changeSortMode(index) {
        this.fetchingData(this.sort_mode_choices[index]);
     }

    render() {
        let is_highlight_topn = (this.state.sort_mode.indexOf("score") != -1);
        return (
            <div>
                <Search />
                <MainSortTab mode="club" changeTab = {this.changeSortMode.bind(this)}/>
                <Sort mode="club" sortColor={is_highlight_topn} unit='分' data={this.state.data} />
            </div>
        );
    }
}

export default MainClub;
